
const express = require("express");//引入模块
const query = require("../util/query.js"); //引入查询模块
const JWT = require('../util/token.js');  //引入jwt--jsonwebtoken第三方库生成Token

let router = express.Router(); //创建空路由器

//==============================================
// 商品功能
//==============================================
// 获取商品列表(分页,检索）
// 访问 GET /product/page
// 参数名	参数说明	备注
// 页号   pageIndex
// 页大小 pageSize 
// 搜索 keyWord
// 分类id category_id
router.get("/page", async (req, res) => {
  try {
    //获取数据
    let { pageIndex, pageSize, keyWord ,category_id } = req.query;
		//console.log(req.query);
    if (!keyWord) keyWord = "";
		category_id = parseInt(category_id) || 0;
    
    //获取数据：起始页码，从1开始
    pageIndex = parseInt(pageIndex);
    pageIndex = pageIndex ? pageIndex : 1;
    //获取数据：每页大小
    pageSize = parseInt(pageSize);
    pageSize = pageSize ? pageSize : 2147483647;  //10
    //计算开始查询的值start
    let start = (pageIndex - 1) * pageSize;

    //建sql语句  
    let sql1 = `select count(*) as count from v_laptop where 1=1 `;
		if(keyWord) sql1 += ` AND title LIKE '%${keyWord}%' `;
		if(category_id) sql1 += ` AND family_id = ${category_id} `;
		
    let sql2 = `SELECT * FROM v_laptop  where 1=1 `;
		if(keyWord) sql2 += ` AND title LIKE '%${keyWord}%' `;
		if(category_id) sql2 += ` AND family_id = ${category_id} `;
    sql2 += ` ORDER BY id LIMIT ${start},${pageSize} `
    let sql = `${sql1} ; ${sql2}`;
    
		//console.log(sql)  //调试输出
    //执行Query
    let result = await query(sql);
    //处理返回数据，（返回记录数量是0也是一种成功），响应对象
    let recordTotal = result[0][0]["count"]; //获取记录总数，第1个SQL语句的执行结果
    let pageTotal = Math.floor(recordTotal / pageSize) + 1; //计算总页数
    let data = result[1];//第2个SQL语句的执行结果     
    res.send({
      code: 1,
      msg: "获取成功",
      recordTotal, //总记录数
      pageIndex,  //页号
      pageSize, //每页大小
      pageTotal,  //总页数
      data
    });
  } catch (error) {
    res.send({ code: -1, msg: error.message });
  }
});


//===============================================
// 根据商品编号获取对应的商品详情
// 参数名	参数说明	备注
// id	商品编号
router.get("/detail", async(req, res) => {
  try{
    //1.1获取数据
    let {id} = req.query;
    id = parseInt(id);
    //验证数据是否为空
    if (!id) throw new Error("商品编号不能为空");

    //执行4个SQL语句，把查询的数据响应给浏览器
    let sql1 = `SELECT * FROM xz_laptop WHERE id=${id}`;
    let sql2 = `SELECT id,laptop_id,sm,md,lg FROM xz_laptop_pic WHERE laptop_id=${id}`;
    let sql3 = `SELECT xz_laptop_family.id,xz_laptop_family.name FROM xz_laptop_family INNER JOIN xz_laptop ON xz_laptop_family.id = xz_laptop.family_id WHERE xz_laptop.id = ${id}`;
    let sql4 = `SELECT id,spec FROM xz_laptop WHERE family_id IN (SELECT family_id FROM xz_laptop WHERE id =${id})`;
    let sql = `${sql1} ; ${sql2} ;${sql3} ; ${sql4}`;   
    //执行Query
    let result = await query(sql);
    
    
    //如果数据查询成功，按要求组装成JSON对象
    let data = result[0][0]; //第1个SQL语句的返回结果的第1条记录（也只有1条记录）
    if (data) {
      data["picList"] = result[1]; //第2个SQL语句的返回结果
      let family = result[2][0]; //第3个SQL语句的返回结果的第一条记录（也只有1条记录）
      data["family"] = family;
      if (data["family"]) data["family"]["laptopList"] = result[3]; //第4个SQL语句的返回结果
    }
    res.send({ code: 1, msg: "获取成功", data: data });        
  }catch (error) {
    res.send({ code: -1, msg: error.message });
  }  
});

//===============================================
//删除单个商品 GET /product/delete
//参数 商品Id
router.get("/delete", async(req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return;
  
  try {
    //获取数据
    let id = req.query.id;
    //验证数据
    if (!id) throw new Error("编号Id不能为空");
    //执行SQL语句
    let sql = `DELETE FROM xz_laptop WHERE id = ${id}`;
    let result = await query(sql);
    //根据sql操作影响的记录行数，判断是否删除成功
    if (result.affectedRows > 0) {
      res.send({ code: 1, msg: `删除成功 ：id=${id}` });
      return;
    }
    throw new Error("记录不存在");
  } catch (error) {
    res.send({ code: -1, msg: error.message });
  }
}); 

//===============================================
//商品修改 / 新增商品 POST /product/update
//参数 ：参见xz_laptop表
//如果id不空则修改，id空则新增
router.post("/update", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return;

  try {
    //获取数据，验证数据
    let product = req.body;		
		delete product.pic;//删除图片字段；另行处理
		
    if (!product.family_id) throw new Error("字段（family_id）不能为空");
    if (!product.name) throw new Error("字段（name）不能为空");
    //如果需要的华话，可以继续对其他字段进行验证

    //创建sql语句，并执行
    let sql = "";
    if (product.id) { //如果参数有id值的，则更新			
      sql = `UPDATE xz_laptop SET ? WHERE id=${product.id}`;
    } else { // 参数无id值，则新增记录
      sql = `INSERT INTO xz_laptop SET ?`;
    }
    let result = await query(sql, [product]);

    //根据sql操作影响的记录行数，判断是否删除成功
    if (result.affectedRows > 0) {
      if (!product.id) product.id = result.insertId; //如果是新增，设置新增的id			
      res.send({ code: 1, msg: "操作成功！", data: product });
      return;
    }
    throw new Error("操作失败");
  } catch (error) {
    res.send({ code: -1, msg: error.message });
  }
});

//==================================================
//导出路由器
module.exports = router;
